package com.yst.system.service.impl;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.yst.common.config.OssConfig;
import com.yst.common.config.RuoYiConfig;
import com.yst.common.constant.Constants;
import com.yst.common.core.domain.AjaxResult;
import com.yst.common.core.domain.entity.SysUser;
import com.yst.common.exception.ServiceException;
import com.yst.common.utils.DateUtils;
import com.yst.common.utils.SecurityUtils;
import com.yst.common.utils.StringUtils;
import com.yst.common.utils.bean.BeanUtils;
import com.yst.common.utils.bean.BeanValidators;
import com.yst.common.utils.oss.AliyunOSSUtil;
import com.yst.system.domain.IndexQueryParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yst.system.mapper.BasItemMapper;
import com.yst.system.domain.BasItem;
import com.yst.system.service.IBasItemService;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Validator;

/**
 * 产品信息Service业务层处理
 *
 * @author hoj
 * @date 2024-05-10
 */
@Service
@Slf4j
public class BasItemServiceImpl implements IBasItemService {
    @Autowired
    private BasItemMapper basItemMapper;

    @Autowired
    protected Validator validator;

    @Autowired
    private OssConfig ossConfig;

    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;

    /**
     * 查询产品信息
     *
     * @param itemId 产品信息主键
     * @return 产品信息
     */
    @Override
    public BasItem selectBasItemByItemId(Long itemId) {
        return basItemMapper.selectBasItemByItemId(itemId);
    }

    /**
     * 查询产品信息列表
     *
     * @param basItem 产品信息
     * @return 产品信息
     */
    @Override
    public List<BasItem> selectBasItemList(BasItem basItem) {
        return basItemMapper.selectBasItemList(basItem);
    }

    /**
     * 新增产品信息
     *
     * @param basItem 产品信息
     * @return 结果
     */
    @Override
    public int insertBasItem(BasItem basItem) {
        checkItemModel(basItem.getItemId(), basItem);

        basItem.setCreateTime(DateUtils.getNowDate());
        return basItemMapper.insertBasItem(basItem);
    }

    /**
     * 修改产品信息
     *
     * @param basItem 产品信息
     * @return 结果
     */
    @Override
    public int updateBasItem(BasItem basItem) {
        checkItemModel(basItem.getItemId(), basItem);
        basItem.setUpdateTime(DateUtils.getNowDate());
        return basItemMapper.updateBasItem(basItem);
    }

    /**
     * 批量删除产品信息
     *
     * @param itemIds 需要删除的产品信息主键
     * @return 结果
     */
    @Override
    public int deleteBasItemByItemIds(Long[] itemIds) {
        return basItemMapper.deleteBasItemByItemIds(itemIds);
    }

    /**
     * 删除产品信息信息
     *
     * @param itemId 产品信息主键
     * @return 结果
     */
    @Override
    public int deleteBasItemByItemId(Long itemId) {
        return basItemMapper.deleteBasItemByItemId(itemId);
    }

    @Override
    public String importItem(List<BasItem> itemList, boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(itemList) || itemList.size() == 0) {
            throw new ServiceException("导入产品数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BasItem item : itemList) {
            try {
                // 验证是否存在这个产品
                BasItem u = basItemMapper.selectOne(new LambdaQueryWrapper<BasItem>().eq(BasItem::getItemModel, item.getItemModel()));
                if (StringUtils.isNull(u)) {
                    item.setCreateBy(operName);
                    item.setCreateTime(new Date());
                    insertBasItem(item);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、产品型号 " + item.getItemModel() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, item);
                    item.setItemId(u.getItemId());
                    item.setUpdateTime(new Date());
                    item.setUpdateBy(operName);
                    updateBasItem(item);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、产品型号" + u.getItemModel() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、产品型号 " + item.getItemModel() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、产品型号" + item.getItemModel() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public String importImg(MultipartFile file) {
        //查看文件类型
        if (!file.getContentType().equalsIgnoreCase("application/x-zip-compressed")) {
            return "请选择zip压缩文件!";
        }
        StringBuilder successMsg = new StringBuilder();
        File tofile = null;
        File pathFile = null;
        try {
            tofile = new File(RuoYiConfig.getProfile() + "/tmp/" + UUID.randomUUID()+".zip");
            pathFile = new File(RuoYiConfig.getProfile() + "/tmp/" + UUID.randomUUID());

            FileUtils.copyInputStreamToFile(file.getInputStream(), tofile);
            try {
                ZipUtil.unzip(tofile, pathFile, Charset.forName("GBK"));
            }catch (Exception e){
                ZipUtil.unzip(tofile, pathFile, Charset.forName("UTF-8"));
            }

            List<File> files = FileUtil.loopFiles(pathFile);
            log.info("上传的图片信息{}",files.stream().map(File::getName).collect(Collectors.toList()));
            int failureNum = 0;
            for (File paramFile : files) {
                //获取文件名
                String fileName = paramFile.getName();
                //获取文件后缀
                String suffix = fileName.substring(fileName.lastIndexOf("."));
                if (!suffix.equals(".png")) {
                    String msg = "<br/>" + fileName + " 文件类型不为png格式! ";
                    successMsg.append(msg);
                    failureNum++;
                    continue;
                }
                String upload = aliyunOSSUtil.upload(paramFile);
                if (StringUtils.isBlank(upload)){
                    String msg = "<br/>" + fileName + " 上传阿里云失败! ";
                    successMsg.append(msg);
                    failureNum++;
                }
            }
            successMsg.insert(0, "恭喜您，图片已导入完成！成功 " + (files.size() - failureNum) + " 条" + (failureNum > 0 ? "，失败数据如下：" : ""));
        } catch (Exception e) {
            log.error("文件解压失败！",e);
            return "文件解压失败！";
        } finally {
            FileUtil.del(pathFile);
            FileUtil.del(tofile);
        }

        return successMsg.toString();
    }



    /**
     * 查看该产品型号是否存在
     *
     * @param itemId
     * @param item
     * @return
     */
    public void checkItemModel(Long itemId, BasItem item) {
        if (StringUtils.isBlank(item.getItemModel())){
            throw new ServiceException("请填写产品型号！");
        }
        //不允许有空格
        item.setItemModel(item.getItemModel().trim());
        Long i = basItemMapper.selectCount(new LambdaQueryWrapper<BasItem>()
                .eq(BasItem::getItemModel, item.getItemModel())
                .ne(null != itemId, BasItem::getItemId, itemId)
        );
        if ( i > 0){
            throw new ServiceException("该产品型号已存在！");
        }
        //更新产品图片路径
        item.setImgUrl(getImgUrl(item.getItemModel()));
    }

    /**
     * 补充产品图片
     * @param itemModel
     * @return
     */
    public String getImgUrl(String itemModel) {
        try {
            return  String.format("%s/%s/%s.png",ossConfig.getFilehost(),ossConfig.getDir(), URLEncoder.encode(itemModel, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("图片编码异常{}",itemModel,e);
        }
        return  String.format("%s/%s/%s.png",ossConfig.getFilehost(),ossConfig.getDir(), itemModel);
    }

    @Override
    public AjaxResult saleByItem(IndexQueryParams indexQueryParams) {
        return AjaxResult.success(basItemMapper.saleByItem(indexQueryParams));
    }


}
